<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/settings.php');

class Template {
    private $template;
    private $values;
    
    public function __construct($template, $values = array()) {
        $this->template = $template;
        $this->values = $values;
    }
    
    public function addValue($key, $value) {
        $this->values[$key]=$value;
    }
    
    public function addValues($values) {
        foreach($values as $key=>$value) {
            $this->addValue($key, $value);
        }
    }
    
    public function render() {
        return Template::renderStatic($this->template, $this->values);
    }
            
    public static function renderStatic($template, $values) {
        
        //El código para stats sólo debe aparecer en producción
        if(Settings::isProduction()) {
            $values['#STATS#'] = '
<script src="http://www.google-analytics.com/ga.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var pageTracker = _gat._getTracker("UA-22177545-1");
pageTracker._initData();
pageTracker._trackPageview();
//]]>
</script>';
        }
        
        $template = Settings::getHome().$template;
        if(file_exists($template)) {
            $file = file_get_contents($template);
            preg_match_all('/#[a-zA-Z0-9_]+#/', $file, $tags);
            foreach($tags[0] as $tag) {
                if(array_key_exists($tag, $values)) {
                    $file = str_replace($tag, $values[$tag], $file);
                }
                else {
                    $file = str_replace($tag, '', $file);
                }
            }
        }
        else {
            throw new Exception('Template not found:'.$template);
        }
        return $file;
        
    }
    
    public static function render404() {
        header("HTTP/1.0 404 Not Found");
        header("Status: 404 Not Found");
        require(Settings::getHome().'/includes/mimetype.php');
        echo Template::renderStatic('/templates/404.xhtml', array());
        exit();
    }
}
?>
